@Configuration@EnableCachingpublic class CacheConfig { @Bean // CacheManager로 진행해도 정상 동작 public RedisCacheManager cacheManager( RedisConnectionFactory redisConnectionFactory ) { // 설정 구성을 먼저 진행한다. // Redis를 이용해서 Spring Cache를 사용할 때 // Redis 관련 설정을 모아두는 클래스 RedisCacheConfiguration configuration = RedisCacheConfiguration .defaultCacheConfig() // null을 캐싱 할것인지 .disableCachingNullValues() // 기본 캐시 유지 시간 (Time To Live) .entryTtl(Duration.ofSeconds(10)) // 캐시를 구분하는 접두사 설정 .computePrefixWith(CacheKeyPrefix.simple()) // 캐시에 저장할 값을 어떻게 직렬화 / 역직렬화 할것인지 .serializeValuesWith( SerializationPair.fromSerializer(RedisSerializer.java()) ); return RedisCacheManager .builder(redisConnectionFactory) .cacheDefaults(configuration) .build(); }}
@EnableCaching
// cacheNames: 메서드로 인해서 만들어질 캐시를 지칭하는 이름// key: 캐시에서 데이터를 구분하기 위해 활용할 값@Cacheable(cacheNames = "itemCache", key = "args[0]")public ItemDto readOne(Long id) { log.info("Read One: {}", id); return repository.findById(id) .map(ItemDto::fromEntity) .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND));}